import redis


class RedisQueue:
    def __init__(self, name, namespace='queue'):
        # redis的默认参数为：host='localhost', port=6379, db=0， 其中db为定义redis database的数量
        pool = redis.ConnectionPool(host='gz-crs-3v22wfs1.sql.tencentcdb.com', port=23148, password='j23QdKGB3js2',
                                    decode_responses=True)
        self.__db = redis.Redis(connection_pool=pool, db=11)
        self.pipeline = self.__db.pipeline()
        self.key = '%s:%s' % (namespace, name)

    def qsize(self):
        return self.__db.llen(self.key)  # 返回队列里面list内元素的数量

    def clear(self):
        self.__db.ltrim(self.key, 1, 0)

    def put(self, item):
        self.__db.rpush(self.key, item)  # 添加新元素到队列最右方

    def ping(self):
        return self.__db.ping()

    def pipe_get_wait(self, timeout=None):
        self.pipeline.blpop(self.key, timeout=timeout)

    def pipe_execute(self):
        result = self.pipeline.execute()
        # print(result)
        # print('--'*100)
        return result


    def get_wait(self, timeout=None):
        item = self.__db.blpop(self.key, timeout=timeout)
        return item

    # def get_more(self):
    #     pipline = self.__db.pipeline()
    #     count = 0
    #     while True:
    #         if self.__db.llen(self.key) > 0:
    #             if count <= 1000:
    #                 pipline.blpop(self.key, timeout=30)
    #                 count += 1
    #             else:
    #                 result = pipline.execute()
    #                 yield result

    def get_nowait(self):
        # 直接返回队列第一个元素，如果队列为空返回的是None
        item = self.__db.lpop(self.key)
        return item


if __name__ == '__main__':
    a = RedisQueue(name='rq')
